package com.house.controller;


import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.house.common.Result;
import com.house.entity.House;
import com.house.service.HouseService;
import com.house.service.ImageService;
import com.house.util.LoginUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.Arrays;
import java.util.List;


/**
 * 房屋控制层
 */
@Controller
@RequestMapping("house")
public class HouseController {

    @Autowired
    HouseService houseService;

    @Autowired
    ImageService imageService;



    /**
     * 房屋管理页
     * @return
     */
    @GetMapping("manage")
    public String manage() {

        return "admin/houseManage";
    }

    @PostMapping("manage/list")
    @ResponseBody
    public List<House> list(House house){
        List<House> houses = houseService.list(Wrappers.<House>query().orderByDesc("create_time"));
        for (House h : houses) {
            houseService.imageProcessor(h);
        }
        return houses;
    }


    /**
     * 添加/更新房屋信息  有ID为更新
     * @param house
     * @return
     */
    @PostMapping("manage/saveOrUpdate")
    @ResponseBody
    public Result saveOrUpdate(House house, HttpServletRequest request){
        if(StrUtil.isEmpty(house.getId())) {
            house.init();
        } else {
            house.setUpdateTime(DateUtil.now());
        }

        houseService.saveOrUpdate(house);

        if(StrUtil.isNotEmpty(house.getImageStr())) {
            imageService.reset(house.getId(), Arrays.asList(house.getImageStr().split(",")));
        }
        return Result.ok();
    }


    /**
     * 房屋信息
     * @param id
     * @return
     */
    @PostMapping("/info")
    @ResponseBody
    public Result info(String id){
        House house = houseService.getById(id);
        return Result.ok(house);
    }


    /**
     * 删除房屋
     * @param id
     * @return
     */
    @PostMapping("/manage/delete")
    @ResponseBody
    public Result delete(@RequestBody List<String> id){
        houseService.removeByIds(id);
        return Result.ok();
    }



    @GetMapping("/create")
    @ResponseBody
    public Result create() {
        if(!"admin".equals(LoginUtil.getLoginUser().getUsername())) {
            return Result.error();
        }
        houseService.createTestData();
        return Result.ok();
    }


    @GetMapping("/createImage")
    @ResponseBody
    public Result createImage() {
        if(!"admin".equals(LoginUtil.getLoginUser().getUsername())) {
            return Result.error();
        }
        imageService.createTestData();
        return Result.ok();
    }


}
